Link to this headingNumbers
Link to this headingInteger Overflow
The example below is bad because most compilers will optimize out that check.
Vulnerable Example:
size_t bytes = n * m;
if
Good Example:
size_t bytes = n * m;
if
Link to this headingInteger Underflow
Link to this headingFloats
Link to this headingRounding Issues
Float values cannot exactly represent many decimal numbers, leading to small discrepancies that compound over time.
Rounding Floats Example:
#Calculating Fees on multiple transactions
= 0.001 # 0.1% fee
= 0
+= 100 * # Adding 1000 fees of $0.10
# Won't be exactly 100
#Expected: 100.0, Actual: 99.9999999999986
Numbers that are reduced by a large amount may loose precision.
Loss of significance Devision:
#Converting ETH to wei and Gwei
= 10000000000005551115123126
= / 1_000_000_000
= / 1_000_000_000_000_000_000
#wei_count: 10000000000005551115123126, gwei_count: 1.0000000000005552e+16, eth_count: 10000000.00000555
A large decimal value may show as truncated because it cant be stored correctly
Representation limitations:
= 0.100000000000000005551115123126
#0.1
#Actual value stored: 1.10000000000000008882
Link to this headingCalculation Issues
Summation Issues:
# Accumulating multiple trades
=
=
#Float sum: 0.30000000000000004
# Compare with Decimal
=
=
#Decimal sum: 0.3
Price Comparison:
# Price comparison in an order matching engine
= 0.3
= 0.1 + 0.2
#Buy price: 0.3
#Sell price: 0.30000000000000004
#Are they equal? False
Order of Operations:
# Fee calculation with compounding issues
= 1234.56
= 0.0015 # 0.15%
# Different ways to calculate the same fee
= *
= / 100
= / 100 * 0.15
#Fee calculation 1: 1.85184
#Fee calculation 2: 1.85184
#Fee calculation 3: 1.8518399999999997